package com.foolishbird.sdk.assist;

import android.content.Context;
import android.content.Intent;

import com.foolishbird.sdk.api.FBSDK;
import com.foolishbird.sdk.utils.WL;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WeChatAppletOperation {

    private static final String TAG = WeChatAppletOperation.class.getSimpleName();

    private static WeChatAppletOperation mInstance;

    private IWXAPI mWXAPI;

    private WeChatAppletOperation() {
    }

    public static synchronized WeChatAppletOperation getInstance() {
        if (mInstance == null) {
            mInstance = new WeChatAppletOperation();
        }
        return mInstance;
    }

    public void registerApp(Context context, String appId) {
        WL.d(TAG, "registerApp =========> weixin appId: " + appId);
        mWXAPI = WXAPIFactory.createWXAPI(context, appId);
        mWXAPI.registerApp(appId);
    }

    public void unregisterApp() {
        if (mWXAPI != null) {
            mWXAPI.unregisterApp();
            mWXAPI = null;
        }
    }

    public boolean isRegisterApp() {
        return mWXAPI != null;
    }

    public boolean handleIntent(Intent intent, IWXAPIEventHandler handler) {
        if (mWXAPI != null) {
            return mWXAPI.handleIntent(intent, handler);
        }
        return false;
    }

    @Deprecated
    public boolean startWeChatApplet(String payInfo) {
        return startWeChatApplet(FBSDK.getInstance().getAppletOriginalId(), payInfo);
    }

    public boolean startWeChatApplet(String originalId, String payInfo) {
        WL.d(TAG, "startWeChatApplet -----> originalId: " + originalId);
        WL.d(TAG, "startWeChatApplet -----> payInfo: " + payInfo);

        if (mWXAPI != null) {
            WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
            req.userName = originalId;
            req.path = payInfo;
            req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;
            return mWXAPI.sendReq(req);
        }

        WL.d(TAG, "startWeChatApplet -----> IWXAPI instance is null.");

        return false;
    }

}
